﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;

namespace QBS.Tools
{
    public class CacheUtil
    {
        private Cache _cache;
        private string _maskkey;
        
        public string MaskKey { get { if (string.IsNullOrEmpty(_maskkey)) { _maskkey = string.Empty; } return _maskkey; } set { _maskkey = value; } }
        public CacheUtil()
        {
            HttpContext current = HttpContext.Current;
            if (current != null)
            {
                _cache = current.Cache;
            }
            else
            {
                _cache = HttpRuntime.Cache;
            }
        }
        public CacheUtil(string mask)
        {
            HttpContext current = HttpContext.Current;
            MaskKey = mask;
            if (current != null)
            {
                _cache = current.Cache;
            }
            else
            {
                _cache = HttpRuntime.Cache;
            }
        }

        public void Clear()
        {
            IDictionaryEnumerator enumerator = _cache.GetEnumerator();
            ArrayList list = new ArrayList();
            while (enumerator.MoveNext())
            {
                list.Add(enumerator.Key);
            }
            foreach (string str in list)
            {
                _cache.Remove(str);
            }
        }

        public void Set(object key, object obj)
        {
            Set(key, obj, null);
        }

        public void Set(object key, object obj, DateTime expir)
        {
            if (obj != null)
            {
                _cache.Insert(MaskKey + key.ToString(), obj, null, expir, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
            }
        }

        public void Set(object key, object obj, CacheDependency dep)
        {
            if (obj != null)
            {
                if (_cache[MaskKey + key.ToString()] != null)
                {
                    _cache[MaskKey + key.ToString()] = obj;
                }
                else
                {
                    _cache.Insert(MaskKey + key.ToString(), obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
                }
            }
        }
        public object Get(object key)
        {
            return _cache[MaskKey + key.ToString()];
        }

        public bool HasKey(string key)
        {
            IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Key.ToString() == key)
                    return true;
            }
            return false;
        }
        public void Remove(object key)
        {
            _cache.Remove(MaskKey + key.ToString());
        }
    }
}
